<template>
  <el-dialog class="assign-role" title="分配角色" :visible="setRoleVisible" @close="handlClick" @open="handleOpen">
    <!-- 这里准备复选框 -->
    <el-checkbox-group v-model="checkList">
      <el-checkbox v-for="item in rolesList" :key="item.id" :label="item.id">{{ item.name }}</el-checkbox>
    </el-checkbox-group>

    <template #footer>
      <el-button type="primary" size="small" @click="clikSubmit">确定</el-button>
      <el-button size="small">取消</el-button>
    </template>
  </el-dialog>
</template>

<script>
import { reqGetRolesList } from '@/api/character'
import { reqGetUSerDetail } from '@/api/user'
import { reqAssignRoles } from '@/api/employess'
export default {
  props: {
    // 控制弹框是否显示
    setRoleVisible: {
      type: Boolean,
      default: false
    },
    // 用户的id 用来查询当前用户的角色信息
    userId: {
      type: String,
      default: null
    }
  },
  data() {
    return {
      checkList: [], // 收集
      rolesList: [], // 所有角色
      loading: false
    }
  },
  created() {

  },
  methods: {
    handlClick() {
      this.$emit('update:setRoleVisible', false)
      this.checkList = []// 关闭弹框时关闭默认项
    },
    // 获取所有角色列表
    async getRolesList() {
      // this.loading = true
      // 保证所有请求同时请求，请求都结束了，才关闭loading
      // Promise.all(([this.getRolesList(), this.getUserDetail()])).then(() => {
      //   this.loading = false
      // })
      const { data: { rows }} = await reqGetRolesList(1, 999)
      this.rolesList = rows
    },
    async getUserDetail() {
      const { data: { roleIds }} = await reqGetUSerDetail(this.userId)
      this.checkList = roleIds
    },
    // 点击确定分配角色
    async clikSubmit() {
      await reqAssignRoles({
        id: this.userId,
        roleIds: this.checkList
      })
      this.$message.success('分配角色成功')
      this.handlClick()
    },
    handleOpen() {
      this.getRolesList()
      this.getUserDetail()
    }
  }
}
</script>
